package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.common.PageResult;
import com.blog.cmrpersonalblog.dto.user.request.*;
import com.blog.cmrpersonalblog.dto.user.response.UserResponse;
import com.blog.cmrpersonalblog.service.SysUserService;
import com.blog.cmrpersonalblog.service.UnifiedFileUploadService;
import com.blog.cmrpersonalblog.enums.FileUploadType;
import com.blog.cmrpersonalblog.service.SysRoleService;
import com.blog.cmrpersonalblog.entity.SysRole;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 用户管理控制器
 * 只有管理员权限可以访问
 */
@Slf4j
@RestController
@RequestMapping("/admin/users")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckRole("admin")
@Validated
public class UserManagementController {

   @Resource
    private SysUserService sysUserService;

   @Resource
    private UnifiedFileUploadService unifiedFileUploadService;

   @Resource
    private SysRoleService sysRoleService;

    /**
     * 获取所有可用角色列表
     */
    @GetMapping("/getRoles")
    public Result<List<SysRole>> getAvailableRoles() {
        log.info("管理员获取可用角色列表");
        try {
            List<SysRole> roles = sysRoleService.getEnabledRoles();
            return Result.success(roles);
        } catch (Exception e) {
            log.error("获取角色列表失败", e);
            return Result.error("获取角色列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    public Result<PageResult<UserResponse>> getUserPage(@Valid UserQueryRequest queryRequest) {
        log.info("管理员查询用户列表: {}", queryRequest);
        try {
            PageResult<UserResponse> pageResult = sysUserService.getUserPage(queryRequest);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return Result.error("查询用户列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询用户详情
     */
    @GetMapping("/{userId}/detail")
    public Result<UserResponse> getUserDetail(@PathVariable @NotNull Long userId) {
        log.info("管理员查询用户详情: userId={}", userId);
        try {
            UserResponse userResponse = sysUserService.getUserDetail(userId);
            if (userResponse == null) {
                return Result.error("用户不存在");
            }
            return Result.success(userResponse);
        } catch (Exception e) {
            log.error("查询用户详情失败", e);
            return Result.error("查询用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建用户
     */
    @PostMapping("/create")
    public Result<Void> createUser(@RequestBody @Valid UserCreateRequest createRequest) {
        log.info("管理员创建用户: userName={}", createRequest.getUserName());
        try {
            // 设置创建人
            String currentUserName = StpUtil.getLoginIdAsString();
            createRequest.setCreateBy(currentUserName);

            boolean success = sysUserService.createUser(createRequest);
            if (success) {
                return Result.success("用户创建成功");
            } else {
                return Result.error("用户创建失败");
            }
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return Result.error("创建用户失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}/update")
    public Result<Void> updateUser(@PathVariable @NotNull Long userId,
                                   @RequestBody @Valid UserUpdateRequest updateRequest) {
        log.info("管理员更新用户: userId={}", userId);
        try {
            // 获取当前登录的管理员ID
            Long currentAdminId = StpUtil.getLoginIdAsLong();

            // 如果更新请求包含角色信息，检查是否为自己分配角色
            if (updateRequest.getRoleIds() != null && !updateRequest.getRoleIds().isEmpty()
                && currentAdminId.equals(userId)) {
                return Result.error("管理员不能为自己分配角色");
            }

            // 设置用户ID和更新人
            updateRequest.setUserId(userId);
            String currentUserName = StpUtil.getLoginIdAsString();
            updateRequest.setUpdateBy(currentUserName);

            boolean success = sysUserService.updateUser(updateRequest);
            if (success) {
                return Result.success("用户更新成功");
            } else {
                return Result.error("用户更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return Result.error("更新用户失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}/delete")
    public Result<Void> deleteUser(@PathVariable @NotNull Long userId) {
        log.info("管理员删除用户: userId={}", userId);
        try {
            boolean success = sysUserService.deleteUser(userId);
            if (success) {
                return Result.success("用户删除成功");
            } else {
                return Result.error("用户删除失败");
            }
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batchDelete")
    public Result<Void> deleteUsers(@RequestBody @NotEmpty List<Long> userIds) {
        log.info("管理员批量删除用户: userIds={}", userIds);
        try {
            boolean success = sysUserService.deleteUsers(userIds);
            if (success) {
                return Result.success("用户批量删除成功");
            } else {
                return Result.error("用户批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除用户失败", e);
            return Result.error("批量删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{userId}/resetPassword")
    public Result<Void> resetPassword(@PathVariable @NotNull Long userId,
                                      @RequestBody @Valid UserPasswordChangeRequest passwordRequest) {
        log.info("管理员重置用户密码: userId={}", userId);
        try {
            // 设置用户ID和操作人
            passwordRequest.setUserId(userId);
            String currentUserName = StpUtil.getLoginIdAsString();
            passwordRequest.setUpdateBy(currentUserName);

            boolean success = sysUserService.resetPassword(passwordRequest);
            if (success) {
                return Result.success("密码重置成功");
            } else {
                return Result.error("密码重置失败");
            }
        } catch (Exception e) {
            log.error("重置用户密码失败", e);
            return Result.error("重置用户密码失败：" + e.getMessage());
        }
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/{userId}/updateStatus")
    public Result<Void> updateUserStatus(@PathVariable @NotNull Long userId,
                                         @RequestParam @NotNull Integer status) {
        log.info("管理员更新用户状态: userId={}, status={}", userId, status);
        try {
            String currentUserName = StpUtil.getLoginIdAsString();
            boolean success = sysUserService.updateUserStatus(userId, status, currentUserName);
            if (success) {
                String statusText = status == 1 ? "启用" : "禁用";
                return Result.success("用户" + statusText + "成功");
            } else {
                return Result.error("用户状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户状态失败", e);
            return Result.error("更新用户状态失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/checkUserName")
    public Result<Boolean> checkUserName(@RequestParam String userName,
                                         @RequestParam(required = false) Long excludeUserId) {
        try {
            boolean exists = sysUserService.isUserNameExists(userName, excludeUserId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查用户名失败", e);
            return Result.error("检查用户名失败：" + e.getMessage());
        }
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/checkEmail")
    public Result<Boolean> checkEmail(@RequestParam String email,
                                      @RequestParam(required = false) Long excludeUserId) {
        try {
            boolean exists = sysUserService.isEmailExists(email, excludeUserId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查邮箱失败", e);
            return Result.error("检查邮箱失败：" + e.getMessage());
        }
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/checkPhone")
    public Result<Boolean> checkPhone(@RequestParam String phonenumber,
                                      @RequestParam(required = false) Long excludeUserId) {
        try {
            boolean exists = sysUserService.isPhonenumberExists(phonenumber, excludeUserId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查手机号失败", e);
            return Result.error("检查手机号失败：" + e.getMessage());
        }
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/{userId}/assignRoles")
    public Result<Void> assignRolesToUser(@PathVariable @NotNull Long userId,
                                          @RequestBody @NotEmpty List<Long> roleIds) {
        log.info("管理员为用户分配角色: userId={}, roleIds={}", userId, roleIds);
        try {
            // 获取当前登录的管理员ID
            Long currentAdminId = StpUtil.getLoginIdAsLong();

            // 检查是否为自己分配角色
            if (currentAdminId.equals(userId)) {
                return Result.error("管理员不能为自己分配角色");
            }

            // 检查用户是否存在
            UserResponse user = sysUserService.getUserDetail(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 验证角色是否存在
            List<SysRole> availableRoles = sysRoleService.getEnabledRoles();
            List<Long> availableRoleIds = availableRoles.stream()
                    .map(SysRole::getId)
                    .toList();

            for (Long roleId : roleIds) {
                if (!availableRoleIds.contains(roleId)) {
                    return Result.error("角色ID " + roleId + " 不存在或已禁用");
                }
            }

            // 更新用户角色
            UserUpdateRequest updateRequest = new UserUpdateRequest();
            updateRequest.setUserId(userId);
            updateRequest.setRoleIds(roleIds);
            updateRequest.setUpdateBy(StpUtil.getLoginIdAsString());

            boolean success = sysUserService.updateUser(updateRequest);
            if (success) {
                return Result.success("角色分配成功");
            } else {
                return Result.error("角色分配失败");
            }
        } catch (Exception e) {
            log.error("分配角色失败", e);
            return Result.error("分配角色失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的角色列表
     */
    @GetMapping("/{userId}/getRoles")
    public Result<List<SysRole>> getUserRoles(@PathVariable @NotNull Long userId) {
        log.info("管理员查询用户角色: userId={}", userId);
        try {
            UserResponse user = sysUserService.getUserDetail(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            List<SysRole> roles = user.getRoles() != null ? user.getRoles() : List.of();
            return Result.success(roles);
        } catch (Exception e) {
            log.error("查询用户角色失败", e);
            return Result.error("查询用户角色失败：" + e.getMessage());
        }
    }

    /**
     * ❌ 已废弃：请使用 POST /api/upload/avatar 统一头像上传接口
     * （管理员可通过该接口上传后再调用用户更新接口）
     */
    @Deprecated
    @PostMapping("/{userId}/uploadAvatar")
    @SaCheckRole("admin")
    public Result<String> uploadUserAvatar(@PathVariable @NotNull Long userId,
                                                       @RequestParam("file") MultipartFile file) {
        return Result.error("此接口已废弃，请使用 POST /api/upload/avatar 统一头像上传接口，然后调用用户更新接口");
    }

    /**
     * 删除用户头像（仅管理员）
     */
    @DeleteMapping("/{userId}/deleteAvatar")
    @SaCheckRole("admin")
    public Result<Void> deleteUserAvatar(@PathVariable @NotNull Long userId) {
        log.info("管理员删除用户头像: userId={}", userId);
        try {
            // 检查用户是否存在
            UserResponse user = sysUserService.getUserDetail(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 删除头像文件
            if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                String relativePath = extractRelativePathFromUrl(user.getAvatar());
                if (relativePath != null) {
                    unifiedFileUploadService.deleteFile(relativePath, FileUploadType.AVATAR);
                }
            }

            // 清空用户头像URL
            UserUpdateRequest updateRequest = new UserUpdateRequest();
            updateRequest.setUserId(userId);
            updateRequest.setAvatar("");
            updateRequest.setUpdateBy(StpUtil.getLoginIdAsString());

            boolean success = sysUserService.updateUser(updateRequest);
            if (success) {
                return Result.success("头像删除成功");
            } else {
                return Result.error("头像删除失败");
            }
        } catch (Exception e) {
            log.error("删除用户头像失败", e);
            return Result.error("删除用户头像失败：" + e.getMessage());
        }
    }

    /**
     * 从文件URL中提取相对路径
     */
    private String extractRelativePathFromUrl(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return null;
        }

        // 假设URL格式为: /files/UserAvatar/avatar_1_20240101120000_abcd1234.jpg
        // 提取相对路径: /UserAvatar/avatar_1_20240101120000_abcd1234.jpg
        int filesIndex = fileUrl.indexOf("/files");
        if (filesIndex != -1) {
            return fileUrl.substring(filesIndex + 6); // 去掉 "/files" 部分
        }

        return null;
    }
}
